package com.wondertek.service.quartz;

import com.wondertek.common.exception.AppException;
import com.wondertek.service.entity.sys.SysJobPo;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;

/**
 * @author: gongjiangtao
 * @date: 2024/9/4 09:29
 * @Description: 定时任务工具类
 * @Version: 1.0
 */
@Slf4j
public class ScheduleUtils {

    /**
     * 获取触发器key
     */
    public static TriggerKey getTriggerKey(String jobId) {
        return TriggerKey.triggerKey(JobInvokeUtil.TASK_CLASS_NAME + jobId);
    }

    /**
     * 得到quartz任务类
     *
     * @param scheduleJob 执行计划
     * @return 具体执行任务类
     */
    private static Class<? extends Job> getQuartzJobClass(SysJobPo scheduleJob) {
        boolean isConcurrent = scheduleJob.getConcurrent().equals(0);
        return isConcurrent ? QuartzJobExecution.class : QuartzDisallowConcurrentExecution.class;
    }

    /**
     * 构建任务键对象
     */
    public static JobKey getJobKey(String jobId) {
        return JobKey.jobKey(JobInvokeUtil.TASK_CLASS_NAME + jobId);
    }

    /**
     * 获取表达式触发器
     */
    public static CronTrigger getCronTrigger(Scheduler scheduler, String jobId) {
        try {
            return (CronTrigger) scheduler.getTrigger(getTriggerKey(jobId));
        } catch (SchedulerException e) {
            log.error("报错:", e);
            throw new AppException("获取定时任务CronTrigger出现异常");
        }
    }

    /**
     * 创建定时任务
     */
    public static void createScheduleJob(Scheduler scheduler, SysJobPo scheduleJob) {
        try {
            Class<? extends Job> jobClass = getQuartzJobClass(scheduleJob);
            // 构建job信息
            String jobId = scheduleJob.getId();
            JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(getJobKey(jobId)).build();

            // 表达式调度构建器
            CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(scheduleJob.getCronExpression());
            cronScheduleBuilder = handleCronScheduleMisfirePolicy(scheduleJob, cronScheduleBuilder);

            // 按新的cronExpression表达式构建一个新的trigger
            CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(getTriggerKey(jobId)).withSchedule(cronScheduleBuilder).build();

            // 放入参数，运行时的方法可以获取
            jobDetail.getJobDataMap().put(JobInvokeUtil.TASK_PROPERTIES, scheduleJob);

            // 判断是否存在
            if (scheduler.checkExists(getJobKey(jobId))) {
                // 防止创建时存在数据问题 先移除，然后在执行创建操作
                scheduler.deleteJob(getJobKey(jobId));
            }

            scheduler.scheduleJob(jobDetail, trigger);

            // 暂停任务
            if (scheduleJob.getStatus().equals(1)) {
                scheduler.pauseJob(ScheduleUtils.getJobKey(jobId));
            }
        } catch (Exception e) {
            throw new AppException("创建定时任务失败", e);
        }
    }

    /**
     * 判断定时任务是否存在
     *
     * @param scheduler
     * @param scheduleJob
     * @return
     */
    public static boolean checkExists(Scheduler scheduler, SysJobPo scheduleJob) {
        try {
            String jobId = scheduleJob.getId();
            return scheduler.checkExists(getJobKey(jobId));
        } catch (Exception e) {
            log.error("异常", e);
            return false;
        }
    }


    /**
     * 更新定时任务
     */
    public static void updateScheduleJob(Scheduler scheduler, SysJobPo scheduleJob) {
        try {
            Class<? extends Job> jobClass = getQuartzJobClass(scheduleJob);
            // 构建job信息
            String jobId = scheduleJob.getId();
            TriggerKey triggerKey = getTriggerKey(jobId);
            // 表达式调度构建器
            CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(scheduleJob.getCronExpression());
            cronScheduleBuilder = handleCronScheduleMisfirePolicy(scheduleJob, cronScheduleBuilder);
            // 按新的cronExpression表达式构建一个新的trigger
            CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(getTriggerKey(jobId)).withSchedule(cronScheduleBuilder).build();
            //
            scheduler.rescheduleJob(triggerKey, trigger);
            // 暂停任务
            if (scheduleJob.getStatus().equals(1)) {
                scheduler.pauseJob(ScheduleUtils.getJobKey(jobId));
            }
        } catch (Exception e) {
            log.error("更新定时任务失败", e);
        }
    }

    /**
     * 立即执行任务
     */
    public static void run(Scheduler scheduler, SysJobPo sysJobPo) {
        try {
            // 参数
            JobDataMap dataMap = new JobDataMap();
            dataMap.put(JobInvokeUtil.TASK_PROPERTIES, sysJobPo);
            scheduler.triggerJob(getJobKey(sysJobPo.getId()), dataMap);
        } catch (SchedulerException e) {
            log.error("立即执行定时任务失败", e);
            throw new AppException("立即执行定时任务失败");
        }
    }

    /**
     * 暂停任务
     */
    public static void pauseJob(Scheduler scheduler, String jobId) {
        try {
            scheduler.pauseJob(getJobKey(jobId));
        } catch (SchedulerException e) {
            log.error("暂停定时任务失败", e);
            throw new AppException("暂停定时任务失败");
        }
    }

    /**
     * 恢复任务
     */
    public static void resumeJob(Scheduler scheduler, String jobId) {
        try {
            scheduler.resumeJob(getJobKey(jobId));
        } catch (SchedulerException e) {
            log.error("暂停定时任务失败", e);
            throw new AppException("暂停定时任务失败");
        }
    }

    /**
     * 删除定时任务
     */
    public static void deleteScheduleJob(Scheduler scheduler, String jobId) {
        try {
            scheduler.deleteJob(getJobKey(jobId));
        } catch (SchedulerException e) {
            log.error("删除定时任务失败", e);
            throw new AppException("删除定时任务失败");
        }
    }

    /**
     * 设置定时任务策略
     */
    public static CronScheduleBuilder handleCronScheduleMisfirePolicy(SysJobPo job, CronScheduleBuilder cb) {
        switch (job.getMisfirePolicy()) {
            case JobInvokeUtil.MISFIRE_DEFAULT:
                return cb;
            case JobInvokeUtil.MISFIRE_IGNORE_MISFIRES:
                // 所有被错过的任务都会被重新执行
                return cb.withMisfireHandlingInstructionIgnoreMisfires();
            case JobInvokeUtil.MISFIRE_FIRE_AND_PROCEED:
                // 将部分被错过的任务合并在一起执行一次，然后再正常执行下一周期的任务
                return cb.withMisfireHandlingInstructionFireAndProceed();
            case JobInvokeUtil.MISFIRE_DO_NOTHING:
                // 所有被错过的任务都会被丢弃
                return cb.withMisfireHandlingInstructionDoNothing();
            default:
                throw new AppException("The task misfire policy '" + job.getMisfirePolicy() + "' cannot be used in cron schedule tasks");
        }
    }
}

